﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Threading;

namespace iSun.ServerFile
{
    [ServiceBehavior(IncludeExceptionDetailInFaults = true, ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class FilesService :IFilesService
    {
        public static List<CusFileInfo> files = new  List<CusFileInfo>();

        #region IFilesService 成员
        public Stream DownloadFileStream(string serverfile, string path)
        {
            CusFileInfo file = null;
            var enumerator = files.Where((t) => t.MapPath == path + "/" + serverfile).GetEnumerator();
            if (enumerator.MoveNext())
            {
                file = enumerator.Current;
            }
            else
            {
                throw new FaultException("非法请求。");
            }
            if (File.Exists(file.filepath))
            {
                var incomingRequest = WebOperationContext.Current.IncomingRequest;
                var outgoingResponse = WebOperationContext.Current.OutgoingResponse;
                long offset = 0, count = file.FileLength;
                if (incomingRequest.Headers.AllKeys.Contains("Range"))
                {
                    var match = System.Text.RegularExpressions.Regex.Match(incomingRequest.Headers["Range"], @"(?<=bytes\b*=)(\d*)-(\d*)");
                    if (match.Success)
                    {
                        outgoingResponse.StatusCode = System.Net.HttpStatusCode.PartialContent;
                        string v1 = match.Groups[1].Value;
                        string v2 = match.Groups[2].Value;
                        if (!match.NextMatch().Success)
                        {
                            if (v1 == "" && v2 != "")
                            {
                                var r2 = long.Parse(v2);
                                offset = count - r2;
                                count = r2;
                            }
                            else if (v1 != "" && v2 == "")
                            {
                                var r1 = long.Parse(v1);
                                offset = r1;
                                count -= r1;
                            }
                            else if (v1 != "" && v2 != "")
                            {
                                var r1 = long.Parse(v1);
                                var r2 = long.Parse(v2);
                                offset = r1;
                                count -= r2 - r1 + 1;
                            }
                            else
                            {
                                outgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
                            }
                        }
                    }

                }
                outgoingResponse.ContentType = "application/force-download";
                outgoingResponse.ContentLength = count;

                Console.WriteLine("开始下载：" + serverfile + "(" + offset + "--" + count + ")");
                CusStreamReader fs = new CusStreamReader(new FileStream(file.filepath, FileMode.Open, FileAccess.Read, FileShare.Read), offset, count);
                fs.Reading += (t) =>
                    {
                        //限速代码,实际使用时可以去掉，或者精确控制
                        Thread.Sleep(300);
                        Console.WriteLine(t);
                    };
                return fs;
            }
            else
            {
                throw new FaultException("没找到文件：" + serverfile);
            }

        }

        public Stream DownloadFileStream(string serverfile, string path, long offset = 0, long count = 0)
        {
            CusFileInfo file = null;
            var enumerator = files.Where((t) => t.MapPath == path + "/" + serverfile).GetEnumerator();
            if (enumerator.MoveNext())
            {
                file = enumerator.Current;
            }
            else
            {
                throw new FaultException("非法请求。");
            }
            if (offset >= file.FileLength)
            {
                throw new FaultException("请求的断点超过了文件最大长度。");
            }
            if (count == 0)
            {
                count = file.FileLength - offset;
            }
            if (File.Exists(file.filepath))
            {
                var outgoingResponse = WebOperationContext.Current.OutgoingResponse;
                outgoingResponse.ContentType = "application/force-download";

                Console.WriteLine("开始下载：" + serverfile + "(" + offset + "--" + count + ")");
                CusStreamReader fs = new CusStreamReader(new FileStream(file.filepath, FileMode.Open, FileAccess.Read, FileShare.Read), offset, count);
                fs.Reading += (t) =>
                {
                    //限速代码,实际使用时可以去掉，或者精确控制
                    Thread.Sleep(300);
                    Console.WriteLine(t);
                };
                return fs;
            }
            else
            {
                throw new FaultException("没找到文件：" + serverfile);
            }

        }

        public List<CusFileInfo> GetFiles()
        {
            return files;
        }
        #endregion
    }
}
